package cn.lxycx.dataterrace.util;

import com.jfinal.plugin.activerecord.Db;

public class OracleCache implements Cache {
	// id,key,value,count,Invalidtime,createtime
	@Override
	public Long incr(String key) {
		String updatesql = "update dbcache set value=value+1 where (invalidtime is null or invalidtime>=sysdate) and key=?";
		String updatesql2 = "update dbcache set value=1,invalidtime='' where key=?";
		String insertsql = "insert into dbcache(id,key,value,createtime) VALUES(dbcache_seq.nextval,?,1,sysdate)";
		if(Db.update(updatesql,key)<=0){//自增没有 失效的数据
			if(Db.update(updatesql2,key)<=0){//可能是因为数据失效导致updatesql更新不成功，尝试重置，如果失败则执行插入
				Db.update(insertsql,key);//如果插入失败
			}
		}
	
		return Long.parseLong(Db.queryStr("select value from dbcache where key = ? ",key));
	}

	@Override
	public Long expire(String key, int time) {
		String updatesql = "update dbcache set invalidtime=sysdate+1/24/3600*? where key = ?";
		String insertsql = "insert into dbcache(id,key,invalidtime,createtime) VALUES(dbcache_seq.nextval,?,sysdate+1/24/3600*?,sysdate)";
		long i = 0;
		if((i = Db.update(updatesql,time,key))<=0){//修改数据失败执行插入
			i = Db.update(insertsql,key,time);
		}
		return i;
	}

	
	@Override
	public boolean isEmpty(String key) {//查询没有失效时间或者失效时间大于当前时间的
		String sql = "select * from dbcache where (invalidtime is null or invalidtime>=sysdate) and key=?";
		return Db.findFirst(sql,key)==null;
	}

	
	
	@Override
	public <T> boolean set(String key, T t) {
		String updatesql = "update dbcache set value=?,invalidtime='' where key = ?";
		String insertsql = "insert into dbcache(id,key,value,createtime) VALUES(dbcache_seq.nextval,?,?,sysdate)";
		int i = 0;
		if((i = Db.update(updatesql,t,key))<=0){//修改数据失败执行插入
			i = Db.update(insertsql,key,t);
		}
		return i>0;
	}

	@Override
	public <T> boolean set(String key, T t, int time) {
		String updatesql = "update dbcache set value=?,invalidtime=sysdate+1/24/3600*? where key = ?";
		String insertsql = "insert into dbcache(id,key,value,invalidtime,createtime) VALUES(dbcache_seq.nextval,?,?,sysdate+1/24/3600*?,sysdate)";
		int i = 0;
		if((i = Db.update(updatesql,t,time,key))<=0){//修改数据失败执行插入
			i = Db.update(insertsql,key,t,time);
		}
		return i>0;
	}

	@Override
	public String get(String key) {
		String sql = "select value from dbcache where (invalidtime is null or invalidtime>=sysdate) and key=?";
		return Db.queryStr(sql,key);
	}
	
	@Override
	public boolean del(String key) {
		return Db.deleteById("dbcache", "key", key);
	}
	
	
	public static void main(String[] args) {
		//jfinalConfig.mainInit();
		Cache c = new OracleCache();
		//System.out.println(cache.isEmpty(intervaltime_key+phone));
		
	}
	

}
